<template>
    <HeaderBar :title="$t('plan.title')" :showLogout="true" type="router" @toBack="toBack" />
    <view class="tab-panel">
        <wd-tabs v-model="active" @change="handleChange" auto-line-width>
            <block v-for="item in tabsList" :key="item.code">
                <wd-tab :title="`${item.desc}`" :name="item.code" :badge-props="item.badgeProps"></wd-tab>
            </block>
        </wd-tabs>
    </view>
    <view class="plan-container">
        <view class="list">
            <view class="item" v-for="(item, index) in goodsList" :key="index" @click="toDetail(item, 1)">
                <!--  <view class="push-tag">Non-official push</view> -->
                <view class="title-line">
                    <view class="no">{{ $t('plan.productName') }}: {{ item.goodsName }}</view>
                    <view class="status">{{ $t('plan.pending') }}</view>
                </view>
                <view class="plan-content">
                    <view class="banner">
                        <image :src="item.goodsPic" />
                    </view>
                    <view class="info">
                        <view class="app-title">
                            <view class="logo">
                                <image mode="widthFix" src="@/static/icon/user.jpg" />
                            </view>
                            <view class="content">
                                <view class="name">{{ $t('plan.amongUs') }}</view>
                                <view class="tips">{{ $t('plan.games') }}</view>
                            </view>
                        </view>
                        <view class="tag">{{ $t('plan.video') }}</view>
                        <view class="tag">{{ $t('plan.landing') }}</view>
                    </view>
                </view>
                <view class="plan-text" v-html="item.goodsDesc"></view>
                <view class="vip-wrap">
                    <view class="top">
                        <wd-icon name="note" color="#fff" size="22px"></wd-icon>
                        {{ userInfo.level === 1 ? $t('mine.star.free') : `VIP${userInfo.level - 1}` }}
                    </view>
                    <view class="bottom">
                        <view class="b-item">
                            {{ $t('plan.dagelijkse') }}
                            <text>{{ item.countOrder }} / {{ item.orderLimit }}</text>
                        </view>
                        <view class="b-item">
                            {{ $t('plan.commissieverhouding') }}
                            <text>{{ userInfo.rebateRatio * 100 }}%</text>
                        </view>
                    </view>
                    <view class="vip-list">
                        <view
                            :class="['v-item', v.level === userInfo.level && 'on']"
                            v-for="v in levelList"
                            :key="v.id"
                        >
                            <view class="name">{{ v.level === 1 ? $t('mine.star.free') : `VIP${v.level - 1}` }}</view>
                            <view class="num">{{ v.price }}</view>
                        </view>
                    </view>
                </view>
                <view class="put-wrap">
                    <view class="put-item">
                        <view class="name">{{ $t('plan.min') }}</view>
                        <view class="price">$ {{ item.minPrice }}</view>
                    </view>
                    <view class="put-item">
                        <view class="name">{{ $t('plan.max') }}</view>
                        <view class="price">$ {{ item.maxPrice }}</view>
                    </view>
                </view>
                <view class="start-btn">
                    <view class="btn-item" @click.stop="onPay(item)">{{ $t('plan.start') }}</view>
                </view>
            </view>
            <view class="item" v-for="(item, index) in list" :key="index" @click="toDetail(item, 2)">
                <!--  <view class="push-tag">Non-official push</view> -->
                <view class="title-line">
                    <view class="no">Order No: {{ item.orderNo }}</view>
                    <view class="status">{{ item.state === 0 ? $t('plan.pending') : $t('plan.completed') }}</view>
                </view>
                <view class="plan-content">
                    <view class="banner">
                        <image :src="item.goodsPic" />
                    </view>
                    <view class="info">
                        <view class="app-title">
                            <view class="logo">
                                <image mode="widthFix" src="@/static/icon/user.jpg" />
                            </view>
                            <view class="content">
                                <view class="name">{{ $t('plan.amongUs') }}</view>
                                <view class="tips">{{ $t('plan.games') }}</view>
                            </view>
                        </view>
                        <view class="tag">{{ $t('plan.video') }}</view>
                        <view class="tag">{{ $t('plan.landing') }}</view>
                    </view>
                </view>
                <view class="plan-text" v-html="item.goodsDesc"></view>
                <view class="put-wrap">
                    <view class="put-item">
                        <view class="name">{{ $t('plan.amount') }}</view>
                        <view class="price">$ {{ item.orderAmount }}</view>
                    </view>
                    <view class="put-item">
                        <view class="name">{{ $t('plan.progress') }}</view>
                        <view class="price"><wd-progress :duration="5" :percentage="item.percentage" /></view>
                    </view>
                </view>
                <view class="plan-time">{{ $t('plan.creationTime') }}: {{ formatDate(item.createTime) }}</view>
            </view>
        </view>
    </view>
    <uni-popup ref="payRef">
        <Pay :goodsInfo="goodsInfo" @onClose="onClose" />
    </uni-popup>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { onLoad, onReachBottom } from '@dcloudio/uni-app';
import HeaderBar from '@/components/HeaderBar';
import Pay from '@/components/Pay/index';
import { NavigateTo, getStorage, setStorage } from '@/utils/common';
import { toLang } from '@/utils/lang';
import { formatDate } from '@/utils/date';
import moment from 'moment';
import { getOrderList } from '@/api/order';
import { getCurrentGoods } from '@/api/goods';
import { getMemberLevel } from '@/api/mine';

const payRef = ref(null) as any;
const page = ref<number>(1);
const pageSize = ref<number>(10);
const isEnd = ref<boolean>(false);
const loading = ref<boolean>(false);

const active = ref<string>('all');

const list = ref([]) as any;
const goodsList = ref([]) as any;
const goodsInfo = ref({}) as any;
const levelList = ref([]) as any;

const userInfo = ref(getStorage('user') || {}) as any;

const tabsList = ref([
    {
        code: 'all',
        desc: toLang('plan.all')
    },
    {
        code: '0',
        desc: toLang('plan.pending')
        // badgeProps: {
        //     modelValue: 2,
        //     right: '-4px'
        // }
    },
    {
        code: '1',
        desc: toLang('plan.completed')
    }
]) as any;

onLoad(() => {
    getGoods();
    getLoad();
    getLevelList();
});

//获取会员等级列表
const getLevelList = async () => {
    const res = await getMemberLevel();
    if (res.code !== 200) {
        return;
    }
    levelList.value = res.data.reverse() || [];
};

//初始化加载
const getLoad = () => {
    getOrder();
};

//获取商品列表
const getGoods = async () => {
    const res = await getCurrentGoods();
    if (res.code !== 200) return false;
    let data: any = res.data;
    data.goodsPic = userInfo.value.filePreviewUrl + data.goodsPic;
    goodsList.value = [data];
};

//获取订单列表
const getOrder = async () => {
    let params = {
        pageNum: page.value,
        pageSize: pageSize.value,
        state: active.value === 'all' ? '' : active.value
    } as any;
    const res = await getOrderList(params);
    if (res.code !== 200) return false;
    let data = res.data.list || [];
    data.forEach(async (item: any) => {
        item.goodsPic = userInfo.value.filePreviewUrl + item.goodsPic;
        item.percentage = await getPercentage(item);
    });

    if (data.length < pageSize.value) {
        isEnd.value = true;
    }
    list.value = [...list.value, ...data];
};

//获取进度
const getPercentage = (item: any) => {
    // 2. 将「创建时间字符串」转换为 Moment 对象（若格式特殊，需手动指定格式，避免解析错误）
    // 方式1：自动解析（适用于标准格式，如 ISO 8601、'YYYY-MM-DD HH:mm:ss'）
    const createTime = moment(formatDate(item.createTime));

    // 方式2：手动指定格式（适用于非标准格式，如 'MM/DD/YYYY HH:mm'，推荐明确格式以避免歧义）
    // const createTime = moment(createTimeStr, 'YYYY-MM-DD HH:mm:ss');

    // 3. 获取「当前时间」的 Moment 对象
    const currentTime = moment();

    // 4. 计算时间差（秒）：currentTime - createTime，单位指定为 'seconds'
    const timeDiffInSeconds = currentTime.diff(createTime, 'seconds');

    if (timeDiffInSeconds > item.orderAmount * 1.5) {
        return 100;
    }
    return Math.ceil((timeDiffInSeconds / (item.orderAmount * 1.5)) * 100);
};

//关闭弹框
const onClose = () => {
    payRef.value.close();
    loading.value = false;
    isEnd.value = false;
    page.value = 1;
    list.value = [];
    goodsList.value = [];
    getGoods();
    getLoad();
};

onReachBottom(() => {
    if (!isEnd.value) {
        page.value++;
        getLoad();
    }
});

//切换tab
const handleChange = (e: any) => {
    active.value = e.name;
    loading.value = false;
    isEnd.value = false;
    page.value = 1;
    list.value = [];
    getLoad();
};

//跳转到详情
const toDetail = (row: any, type: number) => {
    setStorage('goodsDetail', row);
    switch (type) {
        case 1:
            NavigateTo('/pages/plan/productDetail');
            break;
        default:
            setStorage('orderDetail', row);
            NavigateTo('/pages/plan/detail');
            break;
    }
};

//立即投放
const onPay = (row: any) => {
    goodsInfo.value = row;
    payRef.value.open('bottom');
};

//返回
const toBack = () => {
    NavigateTo(`/pages/home/index`);
};
</script>

<style lang="scss" scoped>
.tab-panel {
    position: fixed;
    width: 100%;
    height: 100rpx;
    left: 0;
    top: 98rpx;
    background: #fff;
    z-index: 9;
    ::v-deep .uni-scroll-view {
        -ms-overflow-style: none;
        scrollbar-width: none;
        &::-webkit-scrollbar {
            display: none;
        }
    }
    ::v-deep .wd-tabs__nav {
        &::after {
            content: '';
            position: absolute;
            width: 100%;
            height: 2rpx;
            left: 0;
            bottom: 8rpx;
            background: #e5e5e5;
        }
    }
}
.plan-container {
    padding: 220rpx 30rpx 30rpx;
    background: #fff;
    .list {
        .item {
            border: 1rpx solid #e4e6eb;
            border-radius: 16rpx;
            padding: 25rpx 30rpx;
            margin-bottom: 30rpx;
            .push-tag {
                display: inline-block;
                font-size: 24rpx;
                color: #fff;
                background: #0866ff;
                padding: 12rpx 22rpx;
                border-radius: 10rpx;
            }
            .title-line {
                margin-top: 20rpx;
                display: flex;
                justify-content: space-between;
                .no {
                    font-size: 26rpx;
                }
                .status {
                    font-size: 22rpx;
                    color: #0265d1;
                    background: #ebf5ff;
                    padding: 0 20rpx;
                    line-height: 40rpx;
                    height: 40rpx;
                    border-radius: 20rpx;
                    white-space: nowrap;
                }
            }

            .plan-content {
                display: flex;
                margin-top: 40rpx;
                .banner {
                    flex: 1;

                    image {
                        width: 100%;
                        height: 180rpx;
                        border-radius: 18rpx;
                    }
                }
                .info {
                    width: 260rpx;
                    margin-left: 30rpx;
                    .app-title {
                        display: flex;
                        .logo {
                            width: 68rpx;
                            image {
                                width: 100%;
                                border-radius: 18rpx;
                            }
                        }
                        .content {
                            flex: 1;
                            margin-left: 20rpx;
                            .name {
                                font-size: 26rpx;
                            }
                            .tips {
                                font-size: 20rpx;
                                margin-top: 10rpx;
                            }
                        }
                    }
                    .tag {
                        min-width: 100rpx;
                        text-align: center;
                        display: table;
                        height: 40rpx;
                        line-height: 40rpx;
                        background: #f0f2f5;
                        font-size: 20rpx;
                        margin-top: 14rpx;
                    }
                }
            }
            .plan-text {
                margin-top: 30rpx;
                font-size: 24rpx;
                line-height: 34rpx;
            }
            .vip-wrap {
                margin-top: 20rpx;
                background: #202020;
                border-radius: 22rpx;
                padding: 30rpx;
                color: #fff;
                position: relative;
                .wd-icon {
                    margin-right: 10rpx;
                }
                .bottom {
                    margin-top: 20rpx;
                    .b-item {
                        line-height: 50rpx;
                        font-size: 24rpx;
                        text {
                            color: #d4171e;
                        }
                    }
                }
                .vip-list {
                    position: absolute;
                    right: 50rpx;
                    top: 0;
                    .v-item {
                        color: #7c7f88;
                        font-size: 22rpx;
                        .name {
                            position: relative;
                            &::after {
                                content: '';
                                position: absolute;
                                right: -30rpx;
                                top: 20rpx;
                                width: 14rpx;
                                height: 14rpx;
                                background: #7c7f88;
                                border-radius: 100%;
                            }
                        }
                        &:nth-child(1) {
                            position: absolute;
                            right: 80rpx;
                            top: 20rpx;
                        }
                        &:nth-child(2) {
                            position: absolute;
                            right: 120rpx;
                            top: 70rpx;
                        }
                        &:nth-child(3) {
                            position: absolute;
                            right: 80rpx;
                            top: 120rpx;
                        }
                        &:nth-child(4) {
                            position: absolute;
                            right: 20rpx;
                            top: 170rpx;
                        }
                    }
                    .on {
                        color: #d4171e;
                        .name {
                            position: relative;
                            &::after {
                                content: '';
                                position: absolute;
                                right: -30rpx;
                                top: 20rpx;
                                width: 14rpx;
                                height: 14rpx;
                                background: #d4171e;
                                border-radius: 100%;
                            }
                        }
                    }
                }
            }
            .put-wrap {
                margin-top: 20rpx;
                background: #f0f2f5;
                border-radius: 22rpx;
                padding: 20rpx 30rpx;
                .put-item {
                    display: flex;
                    justify-content: space-between;
                    height: 60rpx;
                    align-items: center;
                    font-size: 24rpx;
                    .price {
                        width: 220rpx;
                        text-align: right;
                    }
                }
            }
            .plan-time {
                margin-top: 20rpx;
                font-size: 28rpx;
            }
            .start-btn {
                display: flex;
                align-items: center;
                justify-content: flex-end;
                margin: 26rpx 0 10rpx;
                .btn-item {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    width: 220rpx;
                    height: 70rpx;
                    background: #0866ff;
                    color: #fff;
                    font-size: 28rpx;
                    border-radius: 44rpx;
                    cursor: pointer;
                    margin-left: 20rpx;
                    &:active {
                        opacity: 0.7;
                    }
                }
            }
        }
    }
}
</style>
